package com.cencat.driver.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cencat.driver.entity.DriverMessage;
import com.cencat.driver.mapper.DriverMessageMapper;
import com.cencat.driver.service.DriverMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 司机消息服务实现类
 * 
 * @author cencat
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DriverMessageServiceImpl extends ServiceImpl<DriverMessageMapper, DriverMessage> implements DriverMessageService {

    private final DriverMessageMapper driverMessageMapper;

    @Override
    public List<DriverMessage> getByDriverId(Long driverId, Long tenantId) {
        return driverMessageMapper.selectByDriverId(driverId, tenantId);
    }

    @Override
    public List<DriverMessage> getByType(Integer type, Long tenantId) {
        return driverMessageMapper.selectByType(type, tenantId);
    }

    @Override
    public List<DriverMessage> getByStatus(Integer status, Long tenantId) {
        return driverMessageMapper.selectByStatus(status, tenantId);
    }

    @Override
    public List<DriverMessage> getUnreadMessages(Long driverId, Long tenantId) {
        return driverMessageMapper.selectUnreadMessages(driverId, tenantId);
    }

    @Override
    public List<DriverMessage> getSystemMessages(Long tenantId) {
        return driverMessageMapper.selectSystemMessages(tenantId);
    }

    @Override
    public List<DriverMessage> getTaskMessages(Long driverId, Long tenantId) {
        return driverMessageMapper.selectTaskMessages(driverId, tenantId);
    }

    @Override
    public List<DriverMessage> getNotificationMessages(Long driverId, Long tenantId) {
        return driverMessageMapper.selectNotificationMessages(driverId, tenantId);
    }

    @Override
    public IPage<DriverMessage> getPageList(Long current, Long size, Long driverId, Integer type, Integer status,
                                          String keyword, LocalDateTime startTime, LocalDateTime endTime, Long tenantId) {
        Page<DriverMessage> page = new Page<>(current, size);
        return driverMessageMapper.selectPageList(page, driverId, type, status, keyword, startTime, endTime, tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMessage(DriverMessage message) {
        try {
            // 设置默认值
            message.setStatus(DriverMessage.Status.UNREAD.getValue());
            message.setCreateTime(LocalDateTime.now());
            message.setUpdateTime(LocalDateTime.now());
            
            int result = driverMessageMapper.insert(message);
            
            log.info("发送司机消息成功: messageId={}, driverId={}, type={}, tenantId={}", 
                    message.getId(), message.getDriverId(), message.getType(), message.getTenantId());
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("发送司机消息异常: driverId={}, type={}, tenantId={}", 
                     message.getDriverId(), message.getType(), message.getTenantId(), e);
            throw new RuntimeException("发送司机消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendSystemMessage(String title, String content, Long tenantId) {
        try {
            DriverMessage message = new DriverMessage();
            message.setType(DriverMessage.Type.SYSTEM.getValue());
            message.setTitle(title);
            message.setContent(content);
            message.setTenantId(tenantId);
            
            return sendMessage(message);
            
        } catch (Exception e) {
            log.error("发送系统消息异常: title={}, tenantId={}", title, tenantId, e);
            throw new RuntimeException("发送系统消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendTaskMessage(Long driverId, String title, String content, Long taskId, Long tenantId) {
        try {
            DriverMessage message = new DriverMessage();
            message.setDriverId(driverId);
            message.setType(DriverMessage.Type.TASK.getValue());
            message.setTitle(title);
            message.setContent(content);
            message.setTaskId(taskId);
            message.setTenantId(tenantId);
            
            return sendMessage(message);
            
        } catch (Exception e) {
            log.error("发送任务消息异常: driverId={}, taskId={}, tenantId={}", driverId, taskId, tenantId, e);
            throw new RuntimeException("发送任务消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendNotificationMessage(Long driverId, String title, String content, Long tenantId) {
        try {
            DriverMessage message = new DriverMessage();
            message.setDriverId(driverId);
            message.setType(DriverMessage.Type.NOTIFICATION.getValue());
            message.setTitle(title);
            message.setContent(content);
            message.setTenantId(tenantId);
            
            return sendMessage(message);
            
        } catch (Exception e) {
            log.error("发送通知消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("发送通知消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSendMessage(List<Long> driverIds, String title, String content, Integer type, Long tenantId) {
        try {
            for (Long driverId : driverIds) {
                DriverMessage message = new DriverMessage();
                message.setDriverId(driverId);
                message.setType(type);
                message.setTitle(title);
                message.setContent(content);
                message.setTenantId(tenantId);
                
                if (!sendMessage(message)) {
                    throw new RuntimeException("批量发送消息失败: driverId=" + driverId);
                }
            }
            
            log.info("批量发送消息成功: 发送{}条消息, type={}, tenantId={}", driverIds.size(), type, tenantId);
            
            return true;
            
        } catch (Exception e) {
            log.error("批量发送消息异常: type={}, tenantId={}", type, tenantId, e);
            throw new RuntimeException("批量发送消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsRead(Long id, Long driverId, Long tenantId) {
        try {
            DriverMessage message = driverMessageMapper.selectById(id);
            if (message == null || !tenantId.equals(message.getTenantId())) {
                return false;
            }
            
            // 检查消息归属
            if (message.getDriverId() != null && !driverId.equals(message.getDriverId())) {
                return false;
            }
            
            int result = driverMessageMapper.markAsRead(id, tenantId);
            
            log.debug("标记消息已读成功: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("标记消息已读异常: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsUnread(Long id, Long driverId, Long tenantId) {
        try {
            DriverMessage message = driverMessageMapper.selectById(id);
            if (message == null || !tenantId.equals(message.getTenantId())) {
                return false;
            }
            
            // 检查消息归属
            if (message.getDriverId() != null && !driverId.equals(message.getDriverId())) {
                return false;
            }
            
            int result = driverMessageMapper.markAsUnread(id, tenantId);
            
            log.debug("标记消息未读成功: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("标记消息未读异常: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchMarkAsRead(List<Long> ids, Long driverId, Long tenantId) {
        try {
            for (Long id : ids) {
                if (!markAsRead(id, driverId, tenantId)) {
                    log.warn("批量标记已读失败: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量标记消息已读异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("批量标记消息已读失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAllAsRead(Long driverId, Long tenantId) {
        try {
            int result = driverMessageMapper.markAllAsRead(driverId, tenantId);
            
            log.info("标记所有消息已读成功: 更新{}条消息, driverId={}, tenantId={}", result, driverId, tenantId);
            
            return result >= 0;
            
        } catch (Exception e) {
            log.error("标记所有消息已读异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("标记所有消息已读失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessage(Long id, Long driverId, Long tenantId) {
        try {
            DriverMessage message = driverMessageMapper.selectById(id);
            if (message == null || !tenantId.equals(message.getTenantId())) {
                return false;
            }
            
            // 检查消息归属
            if (message.getDriverId() != null && !driverId.equals(message.getDriverId())) {
                return false;
            }
            
            int result = driverMessageMapper.deleteById(id);
            
            log.info("删除司机消息成功: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId);
            
            return result > 0;
            
        } catch (Exception e) {
            log.error("删除司机消息异常: messageId={}, driverId={}, tenantId={}", id, driverId, tenantId, e);
            throw new RuntimeException("删除司机消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteMessages(List<Long> ids, Long driverId, Long tenantId) {
        try {
            for (Long id : ids) {
                if (!deleteMessage(id, driverId, tenantId)) {
                    throw new RuntimeException("批量删除消息失败: messageId=" + id);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量删除消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("批量删除消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAllMessages(Long driverId, Long tenantId) {
        try {
            int result = driverMessageMapper.deleteAllMessages(driverId, tenantId);
            
            log.info("删除所有消息成功: 删除{}条消息, driverId={}, tenantId={}", result, driverId, tenantId);
            
            return result >= 0;
            
        } catch (Exception e) {
            log.error("删除所有消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("删除所有消息失败", e);
        }
    }

    @Override
    public Long countUnreadMessages(Long driverId, Long tenantId) {
        try {
            return driverMessageMapper.countUnreadMessages(driverId, tenantId);
        } catch (Exception e) {
            log.error("统计未读消息数量异常: driverId={}, tenantId={}", driverId, tenantId, e);
            return 0L;
        }
    }

    @Override
    public Long countMessagesByType(Long driverId, Integer type, Long tenantId) {
        try {
            return driverMessageMapper.countMessagesByType(driverId, type, tenantId);
        } catch (Exception e) {
            log.error("统计指定类型消息数量异常: driverId={}, type={}, tenantId={}", driverId, type, tenantId, e);
            return 0L;
        }
    }

    @Override
    public Long countTotalMessages(Long driverId, Long tenantId) {
        try {
            return driverMessageMapper.countTotalMessages(driverId, tenantId);
        } catch (Exception e) {
            log.error("统计消息总数异常: driverId={}, tenantId={}", driverId, tenantId, e);
            return 0L;
        }
    }

    @Override
    public Map<String, Object> getMessageStatistics(Long driverId, Long tenantId) {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            Long totalCount = countTotalMessages(driverId, tenantId);
            Long unreadCount = countUnreadMessages(driverId, tenantId);
            Long systemCount = countMessagesByType(driverId, DriverMessage.Type.SYSTEM.getValue(), tenantId);
            Long taskCount = countMessagesByType(driverId, DriverMessage.Type.TASK.getValue(), tenantId);
            Long notificationCount = countMessagesByType(driverId, DriverMessage.Type.NOTIFICATION.getValue(), tenantId);
            
            statistics.put("totalCount", totalCount);
            statistics.put("unreadCount", unreadCount);
            statistics.put("readCount", totalCount - unreadCount);
            statistics.put("systemCount", systemCount);
            statistics.put("taskCount", taskCount);
            statistics.put("notificationCount", notificationCount);
            
            // 计算未读率
            double unreadRate = totalCount > 0 ? (double) unreadCount / totalCount * 100 : 0;
            statistics.put("unreadRate", unreadRate);
            
        } catch (Exception e) {
            log.error("获取消息统计信息异常: driverId={}, tenantId={}", driverId, tenantId, e);
        }
        
        return statistics;
    }

    @Override
    public List<Map<String, Object>> getRecentMessages(Long driverId, Integer limit, Long tenantId) {
        try {
            return driverMessageMapper.selectRecentMessages(driverId, limit, tenantId);
        } catch (Exception e) {
            log.error("获取最近消息异常: driverId={}, limit={}, tenantId={}", driverId, limit, tenantId, e);
            return List.of();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cleanExpiredMessages(Integer expiredDays, Long tenantId) {
        try {
            LocalDateTime expiredTime = LocalDateTime.now().minusDays(expiredDays);
            int result = driverMessageMapper.deleteExpiredMessages(expiredTime, tenantId);
            
            log.info("清理过期消息完成: 清理{}条消息, expiredDays={}, tenantId={}", result, expiredDays, tenantId);
            
            return result >= 0;
            
        } catch (Exception e) {
            log.error("清理过期消息异常: expiredDays={}, tenantId={}", expiredDays, tenantId, e);
            throw new RuntimeException("清理过期消息失败", e);
        }
    }

    @Override
    public List<Map<String, Object>> exportMessages(Long driverId, Integer type, Integer status,
                                                   LocalDateTime startTime, LocalDateTime endTime, Long tenantId) {
        try {
            return driverMessageMapper.exportMessages(driverId, type, status, startTime, endTime, tenantId);
        } catch (Exception e) {
            log.error("导出消息信息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("导出消息信息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importMessages(List<Map<String, Object>> messageList, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMsg = new StringBuilder();
        
        try {
            for (int i = 0; i < messageList.size(); i++) {
                try {
                    Map<String, Object> messageData = messageList.get(i);
                    
                    DriverMessage message = new DriverMessage();
                    message.setDriverId(messageData.get("driverId") != null ? 
                            Long.valueOf(messageData.get("driverId").toString()) : null);
                    message.setType(Integer.valueOf(messageData.get("type").toString()));
                    message.setTitle((String) messageData.get("title"));
                    message.setContent((String) messageData.get("content"));
                    message.setTenantId(tenantId);
                    
                    if (sendMessage(message)) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("第").append(i + 1).append("行：发送失败；");
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("第").append(i + 1).append("行：").append(e.getMessage()).append("；");
                }
            }
            
            result.put("success", true);
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("errorMsg", errorMsg.toString());
            
            log.info("导入消息完成: 成功{}条，失败{}条，tenantId={}", successCount, failCount, tenantId);
            
        } catch (Exception e) {
            log.error("导入消息异常: tenantId={}", tenantId, e);
            result.put("success", false);
            result.put("message", "导入消息失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendTaskAssignmentMessage(Long driverId, Long taskId, String taskCode, String pickupAddress, String deliveryAddress, Long tenantId) {
        try {
            String title = "新任务分配";
            String content = String.format("您有新的配送任务：%s\n取货地址：%s\n配送地址：%s\n请及时处理。", 
                    taskCode, pickupAddress, deliveryAddress);
            
            return sendTaskMessage(driverId, title, content, taskId, tenantId);
            
        } catch (Exception e) {
            log.error("发送任务分配消息异常: driverId={}, taskId={}, tenantId={}", driverId, taskId, tenantId, e);
            throw new RuntimeException("发送任务分配消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendTaskStatusChangeMessage(Long driverId, Long taskId, String taskCode, Integer oldStatus, Integer newStatus, Long tenantId) {
        try {
            String title = "任务状态变更";
            String content = String.format("任务 %s 状态已变更：%s → %s", 
                    taskCode, getStatusName(oldStatus), getStatusName(newStatus));
            
            return sendTaskMessage(driverId, title, content, taskId, tenantId);
            
        } catch (Exception e) {
            log.error("发送任务状态变更消息异常: driverId={}, taskId={}, tenantId={}", driverId, taskId, tenantId, e);
            throw new RuntimeException("发送任务状态变更消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendTaskTimeoutWarningMessage(Long driverId, Long taskId, String taskCode, Integer timeoutMinutes, Long tenantId) {
        try {
            String title = "任务超时提醒";
            String content = String.format("任务 %s 已超时 %d 分钟，请尽快处理。", taskCode, timeoutMinutes);
            
            return sendTaskMessage(driverId, title, content, taskId, tenantId);
            
        } catch (Exception e) {
            log.error("发送任务超时提醒消息异常: driverId={}, taskId={}, tenantId={}", driverId, taskId, tenantId, e);
            throw new RuntimeException("发送任务超时提醒消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendSystemMaintenanceMessage(String title, String content, LocalDateTime maintenanceTime, Long tenantId) {
        try {
            String fullContent = String.format("%s\n维护时间：%s\n请提前做好准备。", 
                    content, maintenanceTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            return sendSystemMessage(title, fullContent, tenantId);
            
        } catch (Exception e) {
            log.error("发送系统维护消息异常: title={}, tenantId={}", title, tenantId, e);
            throw new RuntimeException("发送系统维护消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendDriverStatusChangeMessage(Long driverId, String driverName, Integer oldStatus, Integer newStatus, Long tenantId) {
        try {
            String title = "司机状态变更";
            String content = String.format("司机 %s 状态已变更：%s → %s", 
                    driverName, getDriverStatusName(oldStatus), getDriverStatusName(newStatus));
            
            return sendNotificationMessage(driverId, title, content, tenantId);
            
        } catch (Exception e) {
            log.error("发送司机状态变更消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("发送司机状态变更消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendVehicleAssignmentMessage(Long driverId, String driverName, String vehiclePlateNumber, String vehicleModel, Long tenantId) {
        try {
            String title = "车辆分配通知";
            String content = String.format("司机 %s，您已被分配车辆：%s（%s）\n请及时确认并开始工作。", 
                    driverName, vehiclePlateNumber, vehicleModel);
            
            return sendNotificationMessage(driverId, title, content, tenantId);
            
        } catch (Exception e) {
            log.error("发送车辆分配消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("发送车辆分配消息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendPerformanceReportMessage(Long driverId, String driverName, Map<String, Object> performanceData, Long tenantId) {
        try {
            String title = "绩效报告";
            StringBuilder content = new StringBuilder();
            content.append(String.format("司机 %s 的绩效报告：\n", driverName));
            content.append(String.format("完成任务数：%s\n", performanceData.get("completedTasks")));
            content.append(String.format("完成率：%s%%\n", performanceData.get("completionRate")));
            content.append(String.format("平均配送时间：%s分钟\n", performanceData.get("avgDeliveryTime")));
            content.append("继续保持良好表现！");
            
            return sendNotificationMessage(driverId, title, content.toString(), tenantId);
            
        } catch (Exception e) {
            log.error("发送绩效报告消息异常: driverId={}, tenantId={}", driverId, tenantId, e);
            throw new RuntimeException("发送绩效报告消息失败", e);
        }
    }

    /**
     * 获取任务状态名称
     */
    private String getStatusName(Integer status) {
        if (status == null) return "未知";
        
        switch (status) {
            case 0: return "待分配";
            case 1: return "已分配";
            case 2: return "已接受";
            case 3: return "配送中";
            case 4: return "已完成";
            case 5: return "已取消";
            case 6: return "异常";
            default: return "未知";
        }
    }

    /**
     * 获取司机状态名称
     */
    private String getDriverStatusName(Integer status) {
        if (status == null) return "未知";
        
        switch (status) {
            case 0: return "离线";
            case 1: return "在线";
            case 2: return "忙碌";
            case 3: return "休息";
            case 4: return "停用";
            default: return "未知";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> handleBatchOperations(String operation, List<Long> messageIds, Long driverId, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        
        try {
            switch (operation.toLowerCase()) {
                case "read":
                    for (Long messageId : messageIds) {
                        if (markAsRead(messageId, driverId, tenantId)) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    }
                    break;
                    
                case "unread":
                    for (Long messageId : messageIds) {
                        if (markAsUnread(messageId, driverId, tenantId)) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    }
                    break;
                    
                case "delete":
                    for (Long messageId : messageIds) {
                        if (deleteMessage(messageId, driverId, tenantId)) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    }
                    break;
                    
                default:
                    result.put("success", false);
                    result.put("message", "不支持的操作类型: " + operation);
                    return result;
            }
            
            result.put("success", true);
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("message", String.format("批量%s操作完成", operation));
            
            log.info("批量{}操作完成: 成功{}条，失败{}条，driverId={}, tenantId={}", 
                    operation, successCount, failCount, driverId, tenantId);
            
        } catch (Exception e) {
            log.error("批量{}操作异常: driverId={}, tenantId={}", operation, driverId, tenantId, e);
            result.put("success", false);
            result.put("message", "批量操作失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getMessagesByDateRange(Long driverId, LocalDateTime startTime, LocalDateTime endTime, Long tenantId) {
        try {
            return driverMessageMapper.selectMessagesByDateRange(driverId, startTime, endTime, tenantId);
        } catch (Exception e) {
            log.error("按日期范围获取消息异常: driverId={}, startTime={}, endTime={}, tenantId={}", 
                     driverId, startTime, endTime, tenantId, e);
            return List.of();
        }
    }

    @Override
    public Map<String, Object> getMessageTrendStatistics(String startDate, String endDate, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> trendData = driverMessageMapper.selectMessageTrendStatistics(startDate, endDate, tenantId);
            
            result.put("trendData", trendData);
            
            // 计算总体统计
            long totalMessages = trendData.stream()
                    .mapToLong(data -> Long.parseLong(data.get("messageCount").toString()))
                    .sum();
            
            result.put("totalMessages", totalMessages);
            result.put("avgDailyMessages", trendData.isEmpty() ? 0 : totalMessages / trendData.size());
            
        } catch (Exception e) {
            log.error("获取消息趋势统计异常: startDate={}, endDate={}, tenantId={}", 
                     startDate, endDate, tenantId, e);
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getDriverMessageRanking(String startDate, String endDate, Integer limit, Long tenantId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> rankingData = driverMessageMapper.selectDriverMessageRanking(startDate, endDate, limit, tenantId);
            
            result.put("rankingData", rankingData);
            result.put("totalDrivers", rankingData.size());
            
        } catch (Exception e) {
            log.error("获取司机消息排行异常: startDate={}, endDate={}, limit={}, tenantId={}", 
                     startDate, endDate, limit, tenantId, e);
        }
        
        return result;
    }
}